import 'dart:ffi';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import 'package:fluwx/fluwx.dart';
import 'package:magic_car/jiance/pdf_read.dart';
import 'package:magic_car/jiance/read_PDF.dart';
import 'package:magic_car/user/blance.dart';
import 'package:magic_car/util/HttpHelper.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:toast/toast.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:magic_car/UI/bottom_Menu_page.dart';
import 'package:magic_car/UI/userbottom_Menu_page.dart';

//查看合同
class ContractPage extends StatefulWidget {
  final String url;
  final String oid;
  ContractPage(this.url, this.oid);
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return new web_page_state(this.url, this.oid);
  }
}

class web_page_state extends State<ContractPage> {
  Map userinfo;
  Map order_info;
  String user_role; //1用户，2车商
  String pdf_url;
  String test_type = "保修检测";
  WeChatScene scene = WeChatScene.SESSION;
  String _url; //https://mp.weixin.qq.com/s/i52AMqVSNr7_Wv5suYq9Ig
  final String oid;

  bool canconfirm = false;
  bool canprint = false;
  web_page_state(this._url, this.oid);
  List view_arr = new List();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    view_arr = [
      {
        'title': '微信好友',
        'icon': 'resource/images/user/wechat.jpeg',
        'tag': WeChatScene.SESSION
      },
      {
        'title': '朋友圈',
        'icon': 'resource/images/user/wechat1.jpeg',
        'tag': WeChatScene.TIMELINE
      }
    ];
    loaduserinfo();
    loaddetail();
  }

  backhome() {
    if (user_role == '1') {
      final PageRouteBuilder _homeRoute = new PageRouteBuilder(
        pageBuilder: (BuildContext context, _, __) {
          return UBotomeMenumPage();
        },
      );
      Navigator.pushAndRemoveUntil(
          context, _homeRoute, (Route<dynamic> r) => false);
    } else {
      // return new BotomeMenumPage();
      final PageRouteBuilder _homeRoute = new PageRouteBuilder(
        pageBuilder: (BuildContext context, _, __) {
          return BotomeMenumPage();
        },
      );
      Navigator.pushAndRemoveUntil(
          context, _homeRoute, (Route<dynamic> r) => false);
    }
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(
          "保修合同",
          style: new TextStyle(color: Colors.black),
        ),
        backgroundColor: Colors.white,
        elevation: 0,
        iconTheme: new IconThemeData(color: Colors.black),
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.endFloat,
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          backhome();
        },
        child: Icon(
          Icons.home,
          color: Colors.white,
        ),
        backgroundColor: Color.fromRGBO(27, 182, 251, 1),
      ),
      body: new Center(
          child: Container(
              decoration: new BoxDecoration(
                color: Color.fromRGBO(238, 238, 238, 1),
              ),
              child: Stack(children: <Widget>[
                Align(
                    alignment: Alignment.topCenter,
                    child: Padding(
                        padding: new EdgeInsets.fromLTRB(0, 0, 0, 50),
                        child:
                            //new Image.network(this._url)
                            // child: Text('12')
                            WebView(
                          initialUrl: this._url,
                          javascriptMode: JavascriptMode.unrestricted,
                          // 使用JS没限制
                          debuggingEnabled: true,
                        ))),
                Align(
                  alignment: Alignment.bottomCenter,
                  child: SizedBox(
                    width: double.infinity,
                    height: 45,
                    child: new Row(
                      children: <Widget>[
                        canconfirm
                            ? Expanded(
                                flex: 1,
                                // child: Align(
                                //   // alignment: Alignment.bottomRight,
                                child: Padding(
                                    padding:
                                        new EdgeInsets.fromLTRB(10, 0, 10, 0),
                                    child: new FlatButton(
                                        shape: RoundedRectangleBorder(
                                            side: BorderSide.none,
                                            borderRadius: BorderRadius.all(
                                                Radius.circular(20))),
                                        color: Color.fromRGBO(27, 182, 251, 1),
                                        onPressed: () {
                                          setState(() {});

                                          showAlert();
                                        },
                                        child: new Text(
                                          '上传签名合同',
                                          style: TextStyle(color: Colors.white),
                                        ))))
                            : Text(''),
                        //),
                        canprint
                            ? Expanded(
                                flex: 1,
                                child: Padding(
                                    padding:
                                        new EdgeInsets.fromLTRB(10, 0, 10, 0),
                                    child:
                                        // Align(
                                        //   // alignment: Alignment.bottomLeft,

                                        //     child:
                                        new FlatButton(
                                      shape: RoundedRectangleBorder(
                                          side: BorderSide.none,
                                          borderRadius: BorderRadius.all(
                                              Radius.circular(20))),
                                      color: Color.fromRGBO(225, 102, 82, 1),
                                      onPressed: () {
                                        Clipboard.setData(ClipboardData(
                                            text: order_info['contract']));
                                        Toast.show('链接已复制,请在电脑打开此链接', context);
                                      },
                                      child: new Text('打印合同',
                                          style:
                                              TextStyle(color: Colors.white)),
                                    )))
                            : Text(''),
                      ],
                    ),
                  ),
                ),
                //  Align(
                //   alignment: Alignment.bottomCenter,
                //   child: SizedBox(
                //       width: double.infinity,
                //       height: 45,
                //       child: new RaisedButton.icon(
                //         icon:
                //             new Image.asset('resource/images/user/answer.png'),
                //         label: Text(
                //           '打印合同',
                //           style: TextStyle(fontSize: 15),
                //         ),
                //         color: Color.fromRGBO(278, 182, 251, 1),
                //         textColor: Colors.white,
                //         onPressed: () {
                //           //prints();
                //           showAlert();
                //         },
                //       )),
                // ),

                test_type == '保修检测'
                    ? new Container(height: 0)
                    : Align(
                        alignment: Alignment.bottomLeft,
                        child: SizedBox(
                          width: double.infinity,
                          height: 45,
                          child: Row(
                              crossAxisAlignment: CrossAxisAlignment.center,
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: <Widget>[
                                Padding(
                                    padding:
                                        new EdgeInsets.fromLTRB(0, 0, 10, 10),
                                    child: new RaisedButton.icon(
                                      icon: new Image.asset(
                                          'resource/images/user/answer.png'),
                                      label: Text(
                                        '打印报告',
                                        style: TextStyle(fontSize: 15),
                                      ),
                                      color: Color.fromRGBO(278, 182, 251, 1),
                                      textColor: Colors.white,
                                      onPressed: () {
                                        //prints();
                                        if (this.user_role == '2') {
                                          reportdown(); //车商
                                        } else {
                                          //普通用户
                                          prints();
                                        }
                                      },
                                    )),
                                Padding(
                                    padding:
                                        new EdgeInsets.fromLTRB(10, 0, 0, 10),
                                    child: new RaisedButton.icon(
                                      icon: new Image.asset(
                                          'resource/images/user/answer.png'),
                                      label: Text(
                                        '分享报告',
                                        style: TextStyle(fontSize: 15),
                                      ),
                                      color: Color.fromRGBO(278, 182, 251, 1),
                                      textColor: Colors.white,
                                      onPressed: () {
                                        showModalBottomSheet(
                                            context: context,
                                            builder: (BuildContext context) {
                                              return _shareWidget();
                                            });
                                        //share();
                                        //prints();
                                      },
                                    ))
                              ]),
                        ))
              ]))),
    );
  }

  //分享
  share() {
    String describle = "";
    List carinfo =
        order_info["inspectorItemsResult"]["otherData"]["checkData"][0]["post"];
    var km = ''; //l里程
    var pl = ''; //排量
    var qd = ''; //驱动
    // var fdj=param['bxlc']; //发动鸡
    // var cj=param['bxlc']; //车架号
    // var pf=param['bxlc']; //排放标准
    var lx = ''; //类型
    var gc = ''; //国产、进口
    // var cp=param['bxlc']; //车牌
    for (var item in carinfo) {
      if (item['id'] == "3034") {
        lx = item['value'];
      }
      if (item['id'] == "4035") {
        qd = item['value'];
      }

      if (item['id'] == "4034") {
        gc = item['value'];
      }

      if (item['id'] == "4031") {
        pl = item['value'];
      }

      if (item['id'] == "4030") {
        double temp = double.parse(item['value']) / 10000;
        // km = formatNum(temp, 2) + '万';
        km = item['value'];
      }
    }
    describle = order_info['brand_string']['name'] +
        '/' +
        order_info['cartype_string']['name'] +
        '/' +
        pl +
        '/' +
        qd +
        '/' +
        lx +
        '/' +
        gc +
        '/' +
        km +
        '公里';
    var pics = order_info["inspectorItemsResult"]['pics']; //更改数据构造
    var zhengchezhaopian = "";
    for (var value in pics['post']) {
      if (value['name'] == '整车照片') {
        zhengchezhaopian = value['url'];
      }
    }
    var model = WeChatShareWebPageModel(
      this._url,
      title: '车检报告',
      description: describle,
      //description: '233',
      thumbnail: zhengchezhaopian == ""
          ? WeChatImage.network(zhengchezhaopian)
          : WeChatImage.asset('resource/images/user/logo-n.png'),
      scene: scene,
    );
    shareToWeChat(model);
    shareupdate();
  }

  //确认签名
  confirmsign() async {
    SharedPreferences pref = await SharedPreferences.getInstance();
    String role = pref.getString('role');
    Map<String, String> map = new Map();
    map["bid"] = pref.getString('uid');

    map["oid"] = this.oid;
    map['share'] = "1";

    String url = HttpHelper.API_ConfirmSign;

    HttpHelper.post(url, (data) async {
      if (data != null) {
        print(data);
        Toast.show(data["msg"], context);
        loaddetail();
      }
    }, params: map);
  }

  shareupdate() async {
    //更新订单信息

    SharedPreferences pref = await SharedPreferences.getInstance();
    String role = pref.getString('role');
    Map<String, String> map = new Map();
    map["bid"] = pref.getString('uid');

    map["oid"] = this.oid;
    map['share'] = "1";

    String url = HttpHelper.API_UptBussinessOrder;

    if (role == "1") {
      //检测师的报告
      url = HttpHelper.API_UptOrderEdit;
    }

    HttpHelper.post(url, (data) async {
      if (data != null) {
        print(data);
        //Toast.show(data["msg"], context);

      }
    }, params: map);
  }

  showAlert() {
    showModalBottomSheet(
        context: context,
        builder: (BuildContext context) {
          return Padding(
              padding: new EdgeInsets.fromLTRB(0, 0, 0, 0),
              child: Container(
                height: 130,
                child: new Column(children: <Widget>[
                  new Container(
                      decoration: new BoxDecoration(
                          border: Border(
                              bottom: BorderSide(
                                  width: 1, color: Color(0xffe5e5e5)))),
                      height: 50,
                      child: Center(
                          child: Text('是否确定签名无误！',
                              style: TextStyle(fontSize: 14)))),
                  new Container(
                      decoration: new BoxDecoration(
                          border: Border(
                              bottom: BorderSide(
                                  width: 1, color: Color(0xffe5e5e5)))),
                      height: 40,
                      child: new GestureDetector(
                          behavior: HitTestBehavior.opaque,
                          onTap: () async {
                            Navigator.pop(context);
                            confirmsign();
                          },
                          child: Center(
                              child: Text('确定',
                                  style: TextStyle(
                                      fontSize: 16, color: Colors.red))))),
                  new Container(
                      height: 40,
                      child: new GestureDetector(
                          behavior: HitTestBehavior.opaque,
                          onTap: () {
                            Navigator.pop(context);
                          },
                          child: Center(
                              child:
                                  Text('取消', style: TextStyle(fontSize: 16))))),
                ]),
              ));
        });
  }

  Widget _shareWidget() {
    return new Container(
      height: 160.0,
      child: new Column(
        children: <Widget>[
          new Padding(
            padding: EdgeInsets.fromLTRB(0.0, 10.0, 0.0, 0.0),
            child: new Container(
              height: 100.0,
              child: new GridView.builder(
                gridDelegate: new SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: 2,
                    mainAxisSpacing: 1.0,
                    childAspectRatio: 1.0),
                itemBuilder: (BuildContext context, int index) {
                  var item = view_arr[index];
                  return new GestureDetector(
                      onTap: () {
                        //print(item['tag']);
                        Navigator.of(context).pop();
                        //选择检测师
                        setState(() {
                          scene = item['tag'];
                          share();
                        });
                      },
                      child: new Column(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                          new Padding(
                              padding: EdgeInsets.fromLTRB(0.0, 6.0, 0.0, 6.0),
                              child: new Container(
                                  decoration: new BoxDecoration(
                                    // 底色
                                    //        borderRadius: new BorderRadius.circular((20.0)), // 圆角度
                                    borderRadius: new BorderRadius.circular(
                                        25), // 也可控件一边圆角大小
                                  ),
                                  height: 50,
                                  width: 50,
                                  child: ClipRRect(
                                    borderRadius: BorderRadius.circular(25),
                                    child: FadeInImage.assetNetwork(
                                      placeholder: item['icon'],
                                      image: '',
                                      fit: BoxFit.cover,
                                    ),
                                  ))),
                          Expanded(child: new Text(item['title']))
                        ],
                      ));
                },
                itemCount: view_arr.length,
              ),
            ),
          ),
          new Container(
            height: 0.5,
            color: Colors.blueGrey,
          ),
          new Center(
            child: new Padding(
              padding: EdgeInsets.fromLTRB(0.0, 8.0, 0.0, 8.0),
              child: GestureDetector(
                  behavior: HitTestBehavior.opaque,
                  onTap: () {
                    Navigator.of(context).pop();
                    setState(() {});
                  },
                  child: new Text(
                    '取  消',
                    style:
                        new TextStyle(fontSize: 18.0, color: Colors.blueGrey),
                  )),
            ),
          ),
        ],
      ),
    );
  }

  loaddetail() async {
    //获取订单详情
    Map<String, String> map = new Map();
    map['oid'] = this.oid;
    SharedPreferences pref = await SharedPreferences.getInstance();
    String role = pref.getString('role');

    String api = HttpHelper.API_OrderDetail;
    if (role.toString() != '1') {
      api = HttpHelper.API_BussinessOrderDetail;
    }

    HttpHelper.post(api, (data) async {
      print('111');
      if (data != null) {
        if (data["code"].toString() == "1") {
          setState(() {
            order_info = data['info'];
            test_type = data['info']['test_type'];
          });
          if (data['info']['contract_status'].toString() == "2") {
            setState(() {
              canconfirm = true;
              canprint = false;
            });
          }
          if (data['info']['contract_status'].toString() == "3") {
            setState(() {
              canprint = true;
              canconfirm = false;
            });
          }
        }
      }
    }, params: map);
  }

  //下载报告
  reportdown() {
    if (order_info['is_pay_report'] == '1') {
      //已经支付过
      setState(() {
        // showUrl = true;
        pdf_url = HttpHelper.host +
            '/app/index.php?i=16&j=16&c=entry&m=chemogu&do=mobile&r=car.test_pdf&id=' +
            this.oid +
            '&token=' +
            order_info['report_token'];
        Clipboard.setData(ClipboardData(text: pdf_url));
        Toast.show('链接已复制,请在电脑打开此链接', context);
      });
    } else {
      //
      var user_balance = double.parse(userinfo['balance']);
      var report_fee = double.parse(order_info['report_fee']);
      if (user_balance < report_fee) {
        //充值
        //Toast.show('余额不足，请充值', context);
        showAlert();
      } else {
        update_order();
      }
    }
  }

  showAlertss() {
    showModalBottomSheet(
        context: context,
        builder: (BuildContext context) {
          return Padding(
              padding: new EdgeInsets.fromLTRB(0, 0, 0, 0),
              child: Container(
                height: 130,
                child: new Column(children: <Widget>[
                  new Container(
                      decoration: new BoxDecoration(
                          border: Border(
                              bottom: BorderSide(
                                  width: 1, color: Color(0xffe5e5e5)))),
                      height: 50,
                      child: Center(
                          child: Text('余额不足，是否充值？',
                              style: TextStyle(fontSize: 16)))),
                  new Container(
                      decoration: new BoxDecoration(
                          border: Border(
                              bottom: BorderSide(
                                  width: 1, color: Color(0xffe5e5e5)))),
                      height: 40,
                      child: new GestureDetector(
                          behavior: HitTestBehavior.opaque,
                          onTap: () async {
                            Navigator.pop(context);
                            Navigator.of(context)
                                .push(new MaterialPageRoute(builder: (_) {
                              return new BlancePage();
                            })).then((param) {
                              loaduserinfo();
                            });
                          },
                          child: Center(
                              child: Text('去充值',
                                  style: TextStyle(
                                      fontSize: 16, color: Colors.red))))),
                  new Container(
                      height: 40,
                      child: new GestureDetector(
                          behavior: HitTestBehavior.opaque,
                          onTap: () {
                            Navigator.pop(context);
                          },
                          child: Center(
                              child:
                                  Text('取消', style: TextStyle(fontSize: 16))))),
                ]),
              ));
        });
  }

  update_order() async {
    //更新订单信息
    SharedPreferences pref = await SharedPreferences.getInstance();
    String role = pref.getString('role');
    Map<String, String> map = new Map();
    map["bid"] = pref.getString('uid');

    map["oid"] = this.oid;

    String url = HttpHelper.API_UptBussinessOrder;

    HttpHelper.post(url, (data) async {
      if (data != null) {
        print(data);
        //Toast.show(data["msg"], context);

        if (data["code"].toString() == "1") {
          setState(() {
            pdf_url = HttpHelper.host +
                '/app/index.php?i=16&j=16&c=entry&m=chemogu&do=mobile&r=car.test_pdf&id=' +
                this.oid +
                '&token=' +
                data['info']['token'];
            Clipboard.setData(ClipboardData(text: pdf_url));
            Toast.show('链接已复制,请在电脑打开此链接', context);
          });

          //pref.setStringList('userinfo', data["info"]);

        }
      }
    }, params: map);
  }

  //打印处理
  prints() async {
    //更新订单信息
    SharedPreferences pref = await SharedPreferences.getInstance();
    String role = pref.getString('role');
    Map<String, String> map = new Map();

    map["oid"] = this.oid;

    String url = HttpHelper.API_UptOrderEdit;

    HttpHelper.post(url, (data) async {
      if (data != null) {
        print(data);
        //Toast.show(data["msg"], context);

        if (data["code"].toString() == "1") {
          pdf_url = HttpHelper.host +
              '/app/index.php?i=16&j=16&c=entry&m=chemogu&do=mobile&r=car.go_pdf&id=' +
              this.oid +
              '&uid=' +
              pref.getString('uid');
          Clipboard.setData(ClipboardData(text: pdf_url));
          Toast.show('链接已复制,请在电脑打开此链接', context);

          //pref.setStringList('userinfo', data["info"]);

        } else {
          Toast.show('请求失败，请重试', context);
        }
      }
    }, params: map);

    // SharedPreferences pref = await SharedPreferences.getInstance();
    // pdf_url = HttpHelper.host +
    //     '/app/index.php?i=16&j=16&c=entry&m=chemogu&do=mobile&r=car.go_pdf&id=' +
    //     this.oid +
    //     '&uid=' +
    //     pref.getString('uid');
    // Clipboard.setData(ClipboardData(text: pdf_url));
    // Toast.show('链接已复制,请在电脑打开此链接', context);
    // SharedPreferences pref = await SharedPreferences.getInstance();
    // String role = pref.getString('role');
    // if (role.toString() == '1') {
    //   //普通用户
    // } else {
    //   //车商
    //   //先判断车商余额
    //   var balance = double.parse(userinfo['balance']);
    //   // if(balance>0){

    //   // }
    //   SharedPreferences pref = await SharedPreferences.getInstance();
    //   String role = pref.getString('role');
    //   Map<String, String> map = new Map();
    //   map["id"] = '41';

    //   String url =
    //       'http://ylz.9ok6.com/app/index.php?i=16&j=16&c=entry&m=chemogu&do=mobile&r=car.go_pdf';

    //   HttpHelper.postOtherUrl(url, (data) async {
    //     if (data != null) {
    //       print(data);
    //       if (data['result']['data'].length > 0) {
    //         Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
    //           //return new Pdf_ReadPage(data['result']['data']);
    //           return new Read_Pdf();
    //         }));
    //       }
    //       //Toast.show(data["msg"], context);

    //     }
    //   }, params: map);
    // }
  }

  loaduserinfo() async {
    SharedPreferences pref = await SharedPreferences.getInstance();
    String role = pref.getString('role');
    Map<String, String> map = new Map();
    map["id"] = pref.getString('uid');

    String url = HttpHelper.API_BusinessInfo;
    if (role.toString() == '1') {
      url = HttpHelper.API_Userinfo;
      setState(() {
        user_role = '1';
      });
    } else {
      user_role = '2';
    }

    HttpHelper.post(url, (data) async {
      if (data != null) {
        print(data);
        //Toast.show(data["msg"], context);

        if (data["code"].toString() == "1") {
          setState(() {
            userinfo = data["info"];
          });
          //pref.setStringList('userinfo', data["info"]);

        }
      }
    }, params: map);
  }
}
